#include "messagesrequest.h"

MessagesRequest::MessagesRequest(QObject *parent)
    : ExecutionObjectInterface(parent)
{
    urlPath_ = "http://pcw-textinclass.appspot.com/getMessagesClient";

    cookieData_ = "";

    manager_ = NULL;
}

MessagesRequest::MessagesRequest(QString cookieData, QObject *parent)
    : ExecutionObjectInterface(parent)
{
    urlPath_ = "http://pcw-textinclass.appspot.com/getMessagesClient";

    cookieData_ = cookieData;

    manager_ = NULL;
}

MessagesRequest::~MessagesRequest()
{

}

void MessagesRequest::doInBackground()
{
    manager_ = new QNetworkAccessManager(this);

    if (manager_ == NULL) {
        emit error("Unable to allocate Network Access Manager");
        emit processFinished();
        return;
    }

    QUrl url(urlPath_);
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    request.setRawHeader(tr("Cookie").toUtf8(), cookieData_.toUtf8());

    connect(manager_, SIGNAL(finished(QNetworkReply*)), this, SLOT(onNetworkReply(QNetworkReply*)));

    manager_->get(request);
}

void MessagesRequest::onPostExecute()
{
    emit objectFinished();
}

void MessagesRequest::onNetworkReply(QNetworkReply *reply)
{
    QString responseString = reply->readAll();

    QDomDocument doc;
    QHash<QString, QList<Message> > *data = new QHash<QString, QList<Message> >();

    if (!doc.setContent(responseString)) {
        emit error("Unable to parse XML");
    }
    else {
        QDomNodeList messages = doc.elementsByTagName(tr("message"));

        for (int i = 0; i < messages.size(); i++) {
            QDomNode message = messages.item(i);

            QDomNodeList numberMessageTimestamp = message.childNodes();

            if (numberMessageTimestamp.size() == 3) {
                QString number = numberMessageTimestamp.at(0).firstChild().toText().data();
                QString messageBody = numberMessageTimestamp.at(1).firstChild().toText().data();
                QString timestamp = numberMessageTimestamp.at(2).firstChild().toText().data();
                QList<Message> messageList = data->value(number);

                messageList.append(Message(messageBody, timestamp));

                data->insert(number, messageList);
            }
        }

        QList<QString> keys(data->keys());

        for (int i = 0; i < keys.size(); i++) {
            QList<Message> messageList = data->value(keys.at(i));

            qSort(messageList.begin(), messageList.end(), messageLessThan);

            data->insert(keys.at(i), messageList);
        }

        emit responseData(data);
    }

    emit processFinished();
}
